package pkg

import (
	"gitee.com/jmesyan/impetus/protocol"
)

const (
	PKG_SIZE_BYTES = 4
	PKG_TYPE_BYTES = 4
)

var gLittleEndian bool = false

func SetByteOrder(littleEndian bool) {
	gLittleEndian = littleEndian
}

func GetByteOrder() bool {
	return gLittleEndian
}
/**
 * Package protocol encode.
 *
 * +------+------+------------------+
 * | size | type |       body       |
 * +------+------+------------------+
 *
 */
func Encode(pkgType int, body []byte) *[]byte {
	length := 0
	var buffer *[]byte
	if pkgType == TYPE_DATA {
		length = len(body) - PKG_HEAD_BYTES
		buffer = &body
		(*buffer)[0] = byte(pkgType & 0xff)
		(*buffer)[1] = byte(length >> 16)
		(*buffer)[2] = byte(length >> 8)
		(*buffer)[3] = byte(length)
	} else {
		length = len(body)
		buffer = protocol.GetPoolBuffer(length + PKG_HEAD_BYTES)
		(*buffer)[0] = byte(pkgType & 0xff)
		(*buffer)[1] = byte(length >> 16)
		(*buffer)[2] = byte(length >> 8)
		(*buffer)[3] = byte(length)
		copy((*buffer)[PKG_HEAD_BYTES:], body)
	}
	return buffer
}

/**
 * Package protocol decode.
 * See encode for package format.
 */
func Decode(buffer []byte) (pkgType int, body []byte) {
	pkgType = int(buffer[0])
	body = buffer[PKG_HEAD_BYTES:]
	return
}